package com.bluefox.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import sun.nio.ch.Net;

import javax.annotation.PostConstruct;
import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/4/11  22:18
 */
@Slf4j
public class SnowflakeConfig {

    /**
     * 终端id  10为  通过IPV4 字符串转为Long类型
     */
    private static long workerId;

    /**
     * 数据中心ID
     */
    private static long datacenterId = 1;

    private Snowflake snowflake = IdUtil.createSnowflake(getWorkId(), datacenterId);


    public long snowflakeId() {
        return snowflake.nextId();
    }

    /**
     * 自己传入机器码 和数据中心Id
     *
     * @param workerId
     * @param datacenterId
     * @return
     */
    public long snowflakeId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }

    /**
     * 获取机器id
     *
     * @return
     */
    private static Long getWorkId() {
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for (int b : ints) {
                sums += b;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0, 31);
        }
    }

}
